﻿namespace Api.Controllers;

/// <summary>
/// 操作日志
/// </summary>
[Route("api/[controller]/[action]")]
[ApiController]
[Authorize]
public class OperationLogController(IOperationLogBLL operationLogBLL) : BaseController(operationLogBLL)
{
    private readonly IOperationLogBLL _operationLogBLL = operationLogBLL;

    #region 操作日志列表分页
    /// <summary>
    /// 操作日志列表分页
    /// </summary>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel<List<OperationLogVM>>> QueryPageListAsync([FromBody] OperationLogPageQueryRM pageQuery)
    {
        RefAsync<int> total = 0;
        var list = await _operationLogBLL.QueryPageListAsync(pageQuery, total);
        var ret = new ResultModel<List<OperationLogVM>>
        {
            data = list,
            count = total,
        };
        return ret;
    }
    #endregion

    #region 导出操作日志
    /// <summary>
    /// 导出操作日志
    /// </summary>
    /// <param name="exportQuery">分页查询条件</param>
    /// <returns></returns>
    [HttpPost]
    public async Task<ResultModel> ExportOperationLogAsync([FromBody] ExportOperationLogPageQueryRM exportQuery)
    {
        return await OperationExecuteCustomAsync(async () =>
        {
            var result = new ResultModel();
            var taskmodel = new ExcelTaskModel
            {
                task = Util.CreateGUID(),
                type = 2,
                status = 1
            };
            excelTasks.Add(taskmodel.task, taskmodel);

            string path = "";
            try
            {
                #region 任务
                var list = new List<OperationLogVM>();
                var pageQuery = MapperHelper.Mapper<OperationLogPageQueryRM, ExportOperationLogPageQueryRM>(exportQuery);
                pageQuery.PageIndex = 1;
                pageQuery.PageSize = 50;
                RefAsync<int> total = 0;
                var temp = await _operationLogBLL.QueryPageListAsync(pageQuery, total);
                while (temp.Count > 0)
                {
                    list.AddRange(temp);
                    pageQuery.PageIndex += 1;
                    temp = await _operationLogBLL.QueryPageListAsync(pageQuery, total);
                }

                var data = new Dictionary<string, List<string[]>>();
                var rows = new List<string[]>
                {
                    new string[] { "用户名", "姓名", "用户角色", "日志内容", "操作时间" }
                };

                foreach (var item in list)
                {
                    string[] row =
                    [
                        item.Account,
                        item.Name,
                        item.RoleName,
                        item.Content,
                        item.OperateTime.ToString("yyyy-MM-dd HH:mm:ss"),
                    ];
                    rows.Add(row);
                }
                data.Add("操作日志", rows);

                string fileDir = Path.Combine(AppContext.BaseDirectory, "wwwroot", "excel");
                if (!Directory.Exists(fileDir))
                {
                    Directory.CreateDirectory(fileDir);
                }
                string filepath = Path.Combine(fileDir, "操作日志.xlsx");

                NPOIHelper.ExportToExcel(data, filepath);
                path = "/excel/操作日志.xlsx";
                #endregion
            }
            catch (Exception ex)
            {
                Log.WriteException(ex);
            }
            taskmodel.status = 2;
            taskmodel.path = path;
            excelTasks[taskmodel.task] = taskmodel;

            result.code = 1;
            result.data = taskmodel.task;
            return result;
        }, new AddOperationLogInput { Content = $"导出操作日志" });

    }
    #endregion
}
